import React, {useState, useRef, useEffect, FC} from 'react'
import { Table, Button, Pagination, message } from 'antd';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { connect, Loading, Dispatch, IUserState } from 'umi'
import UserModal from './components/UserModal';
import { editRecord, addRecord } from '../../services/users';
import {ISingleUser, IFormProps} from '../../models/data'

interface IUserPageProps {
    users: IUserState
    dispatch: Dispatch
    userListLoading: boolean
}

const Index: FC<IUserPageProps> = ({users, dispatch, userListLoading}) => {
    const columns:ProColumns<ISingleUser>[] = [
        {
          title: 'Id',
          dataIndex: 'id',
          key: 'id',
          render: (text: any) => <a>{text}</a>,
        },
        {
          title: 'Name',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: 'create_time',
          dataIndex: 'create_time',
          valueType: 'dateTime',
          key: 'create_time',
        },
        {
          title: 'Action',
          key: 'action',
          valueType: 'option',
          render: (text: any, record: ISingleUser) => [
            <Button type="primary" size="small" onClick={() => editModal(record)}>edit</Button>,
            <Button danger size="small">delete</Button>
          ],
        },
    ];

    // 控制弹出框的显示与隐藏
    const [isModalVisible, setIsModalVisible] = useState(false);
    // table 中每一行的记录
    const [record, setRecord] = useState<ISingleUser | undefined>(undefined);

    // 修改信息
    const editModal = (record: ISingleUser) => {
        setIsModalVisible(true)
        setRecord(record)
    }
    

    // 添加信息 
    const handleAdd = () => {
        setRecord(undefined)
        setIsModalVisible(true)
    }

    // 弹出框中的取消按钮
    const handleClose = () => {
        setIsModalVisible(false)
    }

    // 修改 或 新增 表单验证通过提交数据
    const onFinish = async (values: IFormProps) => {
        let id = 0;
        if (record) {
            id = record.id ? record.id : 0
        }
        let serverFun;
        if (id) {
            serverFun = editRecord
        } else {
            serverFun = addRecord
       }
       const result = await serverFun(values, id)
       if (result) {
           // 关闭修改框
            setIsModalVisible(false)
            message.success(`${id === 0 ? '添加' : '修改'}成功`)
            dispatch({
                type: 'users/getRemove',
                payload: {
                    page: users.meta.page,
                    per_page: users.meta.per_page
                }
            })
       }else message.error(`${id === 0 ? '添加' : '修改'}失败`)
    };

    // 当页码发生改变时重新获取数据
    const handlePageNum = (page: number, pageSize?: number) => {
        console.log(page, pageSize);
        dispatch({
            type: 'users/getRemove',
            payload: {
                page,
                per_page: pageSize ? pageSize : users.meta.per_page
            }
        })
    }
    // const handlePageSize = (current: number, size: number) => {
        // console.log(current, size)
        // dispatch({
        //     type: 'users/getRemove',
        //     payload: {
        //         page: current,
        //         per_page: size
        //     }
        // })
    // }

    // 刷新操作
    const reloadHandle = () => {
        dispatch({
            type: 'users/getRemove',
            payload: {
                page: users.meta.page,
                per_page: users.meta.per_page
            }
        })
    }
    return (
        <div className="list-table">
            {/* 表格组件 */}
            <ProTable 
              columns={columns}
              dataSource={users.data}
              rowKey='id'
              loading={userListLoading}
              search={false}
              pagination={false}
              headerTitle="user list"
              toolBarRender={() => [
                <Button type="primary" onClick={handleAdd}>添加</Button>
              ]}
              options={{
                density: true,
                fullScreen: true,
                reload: () => {
                    reloadHandle()
                },
                setting: true 
              }}
            />
            {/* 分页组件 */}
            <Pagination
                total={users.meta.total}
                pageSize={users.meta.per_page}
                showSizeChanger
                showQuickJumper
                showTotal={total => `共 ${total} 条数据`}
                onChange={handlePageNum}
                // onShowSizeChange={handlePageSize}
                current={users.meta.page}
            />
            <UserModal isModalVisible={isModalVisible} handleClose={handleClose} record={record} onFinish={onFinish} />
        </div>
    )
}

const mapStateToProps = ({users, loading}: {users: IUserState, loading: Loading}) => {
    // users 为 namespace 为 users 的model，user: {}
    // 所以从 model 下 返回数据时，最好是一个对象类型的数据，才不会报错 user: { data: [] }
    console.log('users', users, loading);
    return {
        users,
        userListLoading: loading.models.users
    }
}
const mapDispatchToProps = (dispatch:Dispatch) => {
    return {
        dispatch
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Index)